#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


//nc -u -l 172.27.1.12 60000
//nc -u 172.27.1.12 50000
int main(int argc, const char *argv[])
{
    int tcp_socket, con_socket, ret_recv;
    struct sockaddr_in myaddr, peeraddr;
    char buf = 0;
    int fd;

    fd = open("/home/jingwu/Desktop/htop.png", O_CREAT|O_WRONLY|O_TRUNC, 0666);
    if(fd < 0) {
        perror("fail to open");
        exit(1);
    }

    int len;
    tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
    if(tcp_socket < 0) {
        perror("fail to socket");
        exit(1);
    }

    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(50000);
    myaddr.sin_addr.s_addr = inet_addr("172.27.1.12");

    if(-1 == bind(tcp_socket, (struct sockaddr*)&myaddr, sizeof(myaddr))) {
        perror("fail to bind");
        exit(1);
    }

    if(-1 == listen(tcp_socket, 5)) {
        perror("fail to listen");
        exit(1);
    }
    len = sizeof(peeraddr);
    con_socket = accept(tcp_socket, (struct sockaddr*)&peeraddr, &len);
    if(con_socket == -1) {
        perror("fail to accept");
        exit(1);
    }
    while(1) {
        ret_recv = recv(con_socket, &buf, sizeof(buf), 0);
        if(ret_recv < 0) {
            perror("fail to recv");
            exit(1);
        } else if(ret_recv == 0) {
            //close(con_socket);
            break;
        } else {
            write(fd, &buf, 1);
        }
    }

    close(fd);
    close(tcp_socket);
    return 0;
}

